package com.hiyiin.IntelligentHospital.cmn.service;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hiyiin.IntelligentHospital.cmn.dao.DictDao;
import com.hiyiin.IntelligentHospital.cmn.listener.DictListener;
import com.hiyiin.IntelligentHospital.model.cmn.Dict;
import com.hiyiin.IntelligentHospital.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictDao, Dict> implements DictService{

    //根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> getChildData(Long id) {
        QueryWrapper<Dict> qw = new QueryWrapper<Dict>();
        qw.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(qw);
        //向list集合的每个dict对象中设置hashChildren
        dictList.forEach(dict -> {
            dict.setHasChildren(this.isChildren(dict.getId()));
        });
        return dictList;
    }

    @Override
    public void exportDictDict(HttpServletResponse response) {
        //设置下载信息,时操作以下载方式打开
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-Disposition", "attachment;filename="+fileName+".xlsx");

        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        //将Dict转换为DictEeVo
        List<DictEeVo> dictEeVoList = new ArrayList<DictEeVo>();
        dictList.forEach(dict -> {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVoList.add(dictEeVo);
        });

        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导入数据字典
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importDict(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，直接根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> qw = new QueryWrapper<>();
            qw.eq("value",value);
            Dict dict = baseMapper.selectOne(qw);
            return dict.getName();
        }else{//如果dictCode不为空，根据value和dictCode查询
            Dict dict = getDictByDictCode(dictCode);
            QueryWrapper<Dict> qw = new QueryWrapper<>();
            qw.eq("parent_id",dict.getId());
            qw.eq("value",value);
            Dict finalDict = baseMapper.selectOne(qw);
            return finalDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据id获取dict_code
        Dict codeDict = this.getDictByDictCode(dictCode);
        if(codeDict == null){
            return null;
        }
        return this.getChildData(codeDict.getId());
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> qw = new QueryWrapper<>();
        qw.eq("dict_code",dictCode);
        return baseMapper.selectOne(qw);
    }


    //判断id下是否有子节点
    private Boolean isChildren(Long id){
        QueryWrapper<Dict> qw = new QueryWrapper<Dict>();
        qw.eq("parent_id",id);
        Long count = baseMapper.selectCount(qw);
        return count > 0;
    }
}
